package mathExpEvaluator.model.operator;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mathExpEvaluator.model.MathValue;
import mathExpEvaluator.model.Operant;
import mathExpEvaluator.model.Operator;
import mathExpEvaluator.model.exception.InvalidMathValueException;

public class SinOperator implements Operator {
	private final OperatorPriority priority;
	private final int priorityLevel = PRIORITY_LEVEL_SIN;

	private final Pattern pattern = Pattern.compile("SIN(-?\\d+(\\.\\d+)?)");

	public SinOperator(int bc, int pos) {
		this.priority = new OperatorPriority(bc, priorityLevel, pos);
	}

	public MathValue apply(List<MathValue> ops) {
		MathValue v = ops.get(0);
		if(v.getValue() instanceof Double)
			return new MathValue(new Double(Math.sin(v.doubleValue())));
		if(v.getValue() instanceof Integer)
			return new MathValue(new Double(Math.sin((double)v.integerValue())));
		return null;
	}

	public String toString() {
		return "SIN";
	}

	public OperatorPriority getPriority() {
		return this.priority;
	}

	public int getPriorityLevel() {
		return PRIORITY_LEVEL_SIN;
	}

	public Operant getBelongedOperant(String exp)
			throws InvalidMathValueException {
		List<MathValue> values = new ArrayList<MathValue>();
		Matcher matcher = pattern.matcher(exp);
		if (matcher.find()) {
			values.add(new MathValue(matcher.group(1)));
			Operant operant = new Operant(values, this);
			return operant;
		} else
			return null;
	}

	public String getStringForm(List<MathValue> values) {
		return this.toString() + values.get(0).toString();
	}
}
